// import 'dart:convert';
import 'dart:io';

// import 'package:aliyun_log_dart_sdk/aliyun_log_dart_sdk.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hi_cache/flutter_hi_cache.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluwx/fluwx.dart';
import 'package:hktk_app/dao/industry_dao.dart';
import 'package:hktk_app/database/my_database.dart';
import 'package:hktk_app/pages/login/automatic2_page.dart';
import 'package:hktk_app/pages/login/device_ask_page.dart';
import 'package:hktk_app/pages/select/select_exam_page.dart';
// import 'package:hktk_app/test_page/my_calendar.dart';

import 'package:flutter_localizations/flutter_localizations.dart';

// import 'package:hktk_app/test_page/my_video.dart';
import 'package:hktk_app/util/device_util.dart';
import 'package:hktk_app/util/my_util.dart';
import 'package:hktk_app/util/toast_util.dart';

// import 'package:hktk_app/util/yidun_util.dart';
import 'package:http/http.dart' as http show get; // 此处
import 'package:hktk_app/routes.dart';
import 'package:sqflite/sqflite.dart';

import 'dao/my_dao.dart';
import 'navigotr/tab_navigator.dart';

final observer = RouteObserver();

// AliyunLogDartSdk? aliyunLogSdk;
//
// Future<void> initProducer() async {
//   // 配置服务入口Endpoint、Project名称、Logstore名称。您可以通过动态参数配置动态更新Endpoint、Project名称等。
//   LogProducerConfiguration configuration = LogProducerConfiguration(
//       endpoint: 'https://cn-chengdu.log.aliyuncs.com', project: 'log-zhu-cheng-du', logstore: 'nginx-log'
//   );
//   //阿里云访问密钥AccessKey。更多信息，请参见访问密钥。阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维。
//   configuration.accessKeyId = 'LTAI5tFJt28yZQGTXsHXpq5c';
//   configuration.accessKeySecret = 'TW54tWTSBKKVRUIMeIPH7Hi5oqy37w';
//   // configuration.securityToken = 'your access key token'; // 仅当您使用令牌服务（STS）方式获取临时AccessKey时需要配置。
//   aliyunLogSdk = AliyunLogDartSdk();
//   LogProducerResult result = await aliyunLogSdk!.initProducer(configuration);
// }


void main() async {
  // Logger.root.level = Level.ALL; // 设置日志级别
  // Logger.root.onRecord.listen((record) {
  //   // 自定义打印全部属于flutter com.yquestion.zzwx下
  //   print('${record.level.name}: ${record.time}: ${record.message}');
  // });

  // FlutterError.onError = (details, {bool forceReport = false}) {
  //   debugPrint(details.exceptionAsString());
  //   debugPrintStack(stackTrace: details.stack);
  // };

  // debugPaintSizeEnabled = true;

  // 捕获 Dart 层未处理异常
  // PlatformDispatcher.instance.onError = (error, stack) {
  //   _logError(error.toString(), stackTrace: stack);
  //   return true; // 表示已处理
  // };
  // var databasesPath = await getDatabasesPath();
  //
  // String path = ('$databasesPath/demo.db');
  // //
  // // Delete the database
  // // await deleteDatabase(path);
  //
  // // open the database
  // MyDatabase.database = await openDatabase(
  //   path,
  //   version: 1,
  //   onCreate: (Database db, int version) async {
  //     // 创建用户信息表  REAL 浮点数（8字节 IEEE 浮点数）  BLOB |||| NUMERIC   DECIMAL(10,2)  VARCHAR  CHAR
  //     await db.execute(
  //       'CREATE TABLE user (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)',
  //     );
  //   },
  // );
  WidgetsFlutterBinding.ensureInitialized();

  // await initProducer();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  MyApp({super.key});

  @override
  State<StatefulWidget> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // final Fluwx fluwx = Fluwx();
  late bool _isLoading = true;
  late Map<String, dynamic>? internetResponse;


  @override
  void initState() {
    //   initState
    super.initState();
    List<Future> promiseArray = [];
    // WidgetsBinding.instance.addPostFrameCallback(( timeStamp){
    //   initProducer();
    // });

    // MyDao.versionCurrentIos().then((res){
    //   debugPrint("");
    // });
    // Platform.isFuchsia

    // Platform.operatingSystem == "harmonyos";
    // // 获取操作系统的详细版本信息
    // String osVersion = Platform.operatingSystemVersion;

    // 记录崩溃日志
    

    promiseArray.add(Fluwx().registerApi(
      appId: "wx044d8096de012255",
      universalLink: "https://www.yunxuebao.com/zzwxPath/",
      doOnAndroid: true,
      doOnIOS: true,
    ));

    promiseArray.add(HiCache.preInit());

    // iOS如果是首次安装，开始检测网络权限，等待权限完成

    bool wifiPermissions = false;
    // for (int i = 0; i < 5; i++) {
    //   List<ConnectivityResult> connectionsResult =
    //   await (Connectivity().checkConnectivity());
    //   if (connectionsResult.contains(
    //     ConnectivityResult.mobile,
    //   ) ||
    //       connectionsResult.contains(ConnectivityResult.wifi)) {
    //     wifiPermissions = true;
    //     break;
    //   }
    //   await Future.delayed(const Duration(seconds: 1));
    // }
    // List<ConnectivityResult> connectionsResult =
    promiseArray
        .add((Connectivity().checkConnectivity()).then((connectionsResult) {
      if (connectionsResult.contains(
            ConnectivityResult.mobile,
          ) ||
          connectionsResult.contains(ConnectivityResult.wifi)) {
        wifiPermissions = true;
      }
      if (!wifiPermissions) {
        // 提示无网络权限
        return {
          "success": false,
          "wlqx": false,
          "msg": "暂无网络权限，请前往设置打开对应网络权限",
        } as Map<String, dynamic>;
      } else {
        return {
          "success": true,
          "wlqx": true,
        };
      }
    }));

    Future.wait(promiseArray).then((value) async {

      // 测试日志
      // LogProducerResult code = await aliyunLogSdk!.addLog({
      //   // 'str': '我是朱泽文',
      //   // 'int': 12,
      //   // 'double': 12.12,
      //   // 'boolean': true,
      //   // 'map': {'key': 'value', 'inntt': 3333},
      //   // 'array': ['a1', 'a2'],
      //   // 'null': null,
      //   'content': '我是朱泽文'
      // });
      // // debugPrint(code.toString());
      // aliyunLogSdk!.setLogCallback((resultCode, errorMessage, logBytes, compressedBytes) {
      //   // 参数配置错误，需要更新参数。
      //   if (LogProducerResult.parametersInvalid == resultCode) {
      //     debugPrint("");
      //     // 例如更新Endpoint配置。
      //     // aliyunLogSdk!.setEndpoint('your endpoint');
      //     // // 没有配置AccessKey，或配置错误也会触发parametersInvalid。
      //     // aliyunLogSdk!.setAccessKey('your access key id', 'your access key secret', securityToken: 'your token');
      //     //
      //   }
      //
      //   // 授权过期，需要更新AccessKey。
      //   if (LogProducerResult.sendUnauthorized == resultCode) {
      //     debugPrint("");
      //     // aliyunLogSdk!.setAccessKey('your access key id', 'your access key secret', securityToken: 'your token');
      //   }
      //   debugPrint("");
      // });


      internetResponse = value[2];
      // if (!internetResponse!["wlqx"]) {
      //   // 如果没有网络，提示一下
      //   WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      //     if (mounted) {
      //       ToastUtil.show(context: context, msg: internetResponse!["msg"]);
      //     }
      //   });
      // }
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }).catchError((err) {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        if (mounted) {
          showDialog(
            context: context,
            builder: (context) => AlertDialog(
              title: Text('未知错误'),
              content: Text('未知错误，请稍后重试'),
              actions: [
                TextButton(
                  onPressed: Navigator.of(context).pop,
                  child: Text('确定'),
                )
              ],
            ),
          );
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: Size(360, 690),
      builder: (context, child) => MaterialApp(
        // navigatorObservers: [MyRouteObserver()],
        localizationsDelegates: [
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
        ],
        locale: Locale('zh', 'CN'),
        supportedLocales: [Locale('en', 'US'), Locale('zh', 'CN')],
        debugShowCheckedModeBanner: false,
        title: '中震网校',
        // theme: ThemeData(
        //   colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        // ),
        routes: routes,
        navigatorObservers: [observer],
        // home: Scaffold(
        //   body: MyVideo(),
        // ),

        // home:Text("home")
        home: _isLoading
            ? Scaffold(
                backgroundColor: Colors.white,
                body: Center(child: CircularProgressIndicator()))
            : possibleAction(),
      ),
    );
  }

  Widget possibleAction() {
    // // 没有网络权限，进入首页
    if (internetResponse!["wlqx"]) {
      if (DeviceUtil.getDeviceKey() == null) {
        return const DeviceAskPage();
        // return Text("DeviceAskPage");
      } else {
        // 登录
        if (getToken() == null) {
          return const Automatic2Page();
          // return  Text("Automatic2Page");
        }
      }
      // 这里以TabNavigator作为首页
      // 必须选中某考试才行
      if (IndustryDao.isInitExamKey()) {
        return TabNavigator();
      } else {
        return SelectExamPage();
      }
    } else {
      return Scaffold(
          backgroundColor: Colors.white, body: Container(
        child: Center(child: Text("无网络"),),
      ));
    }
  }

// _initFluwx() async {
//   await fluwx.registerApi(
//     appId: 'wxd930ea5d5a258f4f',
//     doOnAndroid: true,
//     doOnIOS: true,
//     universalLink: 'https://your.univerallink.com/link/',
//   );
//   var result = await fluwx.isWeChatInstalled;
//   debugPrint('is installed $result');
// }
  Future<bool> isNetworkReachable() async {
    try {
      final result = await http
          .get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'));
      return result.statusCode >= 200 && result.statusCode < 300;
    } catch (e) {
      return false;
    }
  }

// 提示无法访问互联网
  void _showNoInternetAccessDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('无法访问互联网'),
        content: Text('当前网络无法访问外网，请检查网络设置或尝试其他网络'),
        actions: [
          TextButton(
            onPressed: Navigator.of(context).pop,
            child: Text('确定'),
          )
        ],
      ),
    );
  }
}
